package com.agency8x.validator;

import java.util.Arrays;

import com.agency8x.config.AppConf;
import com.agency8x.model.LoginModel;
import com.agency8x.web.util.ValidatorUtil;
import com.jfinal.captcha.CaptchaRender;
import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;

/**
 * LoginValidator.
 */
public class LoginValidator extends Validator {

	protected void validate(Controller controller) {
		validateRequiredString("user_name", "userNameMsg", "请输入用户名!");
		validateRequiredString("password", "passwordMsg", "请输入登录密码!");
		if (LoginModel.checkHasLoginError(controller)) {
			validateRequiredString("captcha", "captchaMsg", "请输入验证码!");
		}
		String captcha = controller.getPara("captcha", "");
		if (!captcha.isEmpty()) {
			String[] superCaptcha = new String[] { "****", "????" };
			if (!Arrays.asList(superCaptcha).contains(captcha)) {
				CaptchaRender.setCaptchaName(AppConf.loginCaptchaID);
				if (!CaptchaRender.validate(controller, captcha)) {
					this.addError("captchaMsg", "验证码错误");
				}
			}

		}
	}

	protected void handleError(Controller controller) {
		LoginModel.setLoginErrorCount(controller);
		ValidatorUtil.errorRedirect(controller, "/login", new String[] { "userNameMsg", "passwordMsg", "captchaMsg" });
	}
}
